/*
 * @Project Name: spring-boot
 * @File Name: UserService
 * @Package Name: com.hhly.spring.boot.cache
 * @Date: 2017/12/13 17:52
 * @Creator: linshixing-1199
 * @line------------------------------
 * @修改人:
 * @修改时间:
 * @修改内容:
 */

package com.sm.shoplook.service.system.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sm.shoplook.constant.Constant;
import com.sm.shoplook.constant.ResultMessage;
import com.sm.shoplook.dao.mapper.system.UserMapper;
import com.sm.shoplook.dao.mapper.system.UserRoleMapper;
import com.sm.shoplook.domain.system.User;
import com.sm.shoplook.domain.system.UserRole;
import com.sm.shoplook.service.system.UserService;
import com.sm.shoplook.shiro.Principal;
import com.sm.shoplook.vo.base.ApiException;
import com.sm.shoplook.vo.base.ApiResult;
import com.sm.shoplook.vo.system.user.req.UserPageSearchReqVo;
import com.sm.shoplook.vo.system.user.req.UserSaveReqVo;
import com.sm.shoplook.vo.system.user.resp.UserRoleRespVo;

/**
 * @author chenpy-1072
 * @desc UserService
 * @date 2017/12/13 17:52
 * @see
 */
@Service
public class UserServiceImpl implements UserService {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;

	@Override
	public ApiResult<List<User>> selectUserByUserName(String userName) {
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, userMapper.selectUsersByUserName(userName));
	}

	@Override
	public ApiResult<PageInfo<User>> selectUsersPage(UserPageSearchReqVo userSearchReqVo) {
		PageHelper.startPage(userSearchReqVo.getOffset(), userSearchReqVo.getPageSize());
		List<User> users = userMapper.selectUsersPage(userSearchReqVo);
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, new PageInfo<>(users));
	}

	@Override
	public ApiResult deleteUsers(String[] idList) throws ApiException {
		int i = userMapper.deleteUsers(idList);
		if (i < 1) {
			throw new ApiException();
		}
		return new ApiResult(ResultMessage.RESULT_SUCCESS_1);
	}

	@Override
	public ApiResult saveUser(UserSaveReqVo userSaveReqVo) throws ApiException {
		User user = new User();
		BeanUtils.copyProperties(userSaveReqVo, user);
		user.setUpdateTime(new Date());
		Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
		user.setUpdateUser(principal.getUserName());
		int i;
		String pwd = (new SimpleHash("MD5", user.getPassword(),
				ByteSource.Util.bytes(new String(Hex.encode(Constant.HASH_KEY.getBytes()))), 999)).toString();
		// 添加用户
		if (userSaveReqVo.getId() == null) {
			// 判断用户名是否已存在
			List<User> users = userMapper.selectUsersByUserName(userSaveReqVo.getUserName());
			if (CollectionUtils.isNotEmpty(users)) {
				return new ApiResult(ResultMessage.USER_NAME_EXISTS);
			}
			user.setPassword(pwd);
			user.setCreateTime(new Date());
			user.setUserCode("USER_" + System.currentTimeMillis());
			i = userMapper.insertUser(user);
			if (StringUtils.isEmpty(userSaveReqVo.getRoleCode())) {
				return new ApiResult(ResultMessage.RESULT_SUCCESS_1);
			}
			UserRole userRole = new UserRole();
			userRole.setRoleCode(userSaveReqVo.getRoleCode());
			userRole.setUserId(user.getId());
			userRoleMapper.insertSelective(userRole);
		} else {
			// 判断用户名是否已存在
			List<User> users = userMapper.selectUsersByUserName(userSaveReqVo.getUserName());
			if (CollectionUtils.isNotEmpty(users) && !userSaveReqVo.getId().equals(users.get(0).getId())) {
				return new ApiResult(ResultMessage.USER_NAME_EXISTS);
			}
			// 修改用户
			UserRoleRespVo userRoleRespVo = userMapper.selectUserRoleByUserId(userSaveReqVo.getId());
			// 不需要进行密码修改
			if (!userRoleRespVo.getPassword().equals(user.getPassword())) {
				user.setPassword(pwd);
			}
			i = userMapper.updateByPrimaryKeySelective(user);
			if (StringUtils.isEmpty(userSaveReqVo.getRoleCode())) {
				return new ApiResult(ResultMessage.RESULT_SUCCESS_1);
			}
			if (StringUtils.isEmpty(userRoleRespVo.getRoleCode())) {
				UserRole userRole = new UserRole();
				userRole.setRoleCode(userSaveReqVo.getRoleCode());
				userRole.setUserId(user.getId());
				userRoleMapper.insertSelective(userRole);
				return new ApiResult(ResultMessage.RESULT_SUCCESS_1);
			}
			// 修改角色
			UserRole userRole = new UserRole();
			userRole.setRoleCode(userSaveReqVo.getRoleCode());
			userRole.setUserId(userRoleRespVo.getId());
			userRole.setId(userRoleRespVo.getUserRoleId());
			userRoleMapper.updateByPrimaryKey(userRole);
			if (userSaveReqVo.getId().equals(principal.getUserId())) {
				return new ApiResult(ResultMessage.LOGOUT_LOGIN);
			}
		}
		if (i < 1) {
			throw new ApiException();
		}
		return new ApiResult(ResultMessage.RESULT_SUCCESS_1);
	}

	@Override
	public ApiResult<UserRoleRespVo> selectUserRoleByUserId(Integer userId) {
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, userMapper.selectUserRoleByUserId(userId));
	}
}
